package com.dragon.concurrent.demo.readandwrite;

import java.util.Random;
import java.util.concurrent.TimeUnit;

public class WriteWorker extends Thread {

    private static final Random random = new Random(System.currentTimeMillis());

    private final ShareData data;

    private final String filler;

    private int index = 0;

    public WriteWorker(ShareData data, String filler) {
        this.data = data;
        this.filler = filler;
    }

    @Override
    public void run() {
        while (true) {
            try {
                data.write(nextChar());
                TimeUnit.MILLISECONDS.sleep(random.nextInt(1000));
            } catch (InterruptedException e) {
                e.printStackTrace();
                break;
            }
        }
    }

    private char nextChar() {
        char c = filler.charAt(index++);
        if (index >= filler.length()) {
            index = 0;
        }

        return c;
    }
}
